<template>
  <div class="g-content-map">
    <!-- <device-map></device-map>
    <device-state></device-state>-->
    <!-- add/edit device -->
    <div class="app-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
      <div class="g-content-title">{{ !id ? '新增设备' : '编辑设备' }}</div>

      <el-form
        ref="deviceForm"
        :model="form"
        :rules="rules"
        label-width="130px"
        size="small"
      >
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="设备编号" prop="equipmentId">
              <el-col>
                <el-input
                  v-model="form.equipmentId"
                  placeholder="请输入设备编号"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col>
            <el-form-item label="所属" prop="areaId">
              <areaSelect
                :selectModel="form.areaId"
                :areaIds="areaIds"
                @onAreaId01Change="onAreaFirstChildChange"
                @onComponentChildChange="onAreaSecondChildChange"
                hideThird="true"
              ></areaSelect>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col>
            <el-form-item label="选择场景" prop="moduleId">
              <sceneSelect
                :selectModel="form.moduleId"
                :modTypes="modTypes"
                :parentArr="parentList"
                :childArr="childList"
                @firstSelectChange="firstSelectChange"
                @secondSelectChange="secondSelectChange"
              ></sceneSelect>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col>
            <el-form-item label="设备型号" prop="equipmentModel">
              <el-col>
                <el-input
                  v-model="form.equipmentModel"
                  placeholder="请输入设备型号"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="15">
          <el-col>
            <el-form-item label="设备类型" prop="equipmentType">
              <deviceTypeSelect :selectModel="form.equipmentType" @onDeviceChange="onDeviceChange"></deviceTypeSelect>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="设备名称" prop="equipmentName">
              <el-col>
                <el-input
                  v-model="form.equipmentName"
                  placeholder="请输入设备名称"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col>
            <el-form-item label="制造商" prop="equipmentMaker">
              <el-col>
                <el-input
                  v-model="form.equipmentMaker"
                  placeholder="请输入制造商"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col>
            <el-form-item label="设备状态">
              <el-col>
                <el-select
                  v-model="form.equipmentState"
                  placeholder="请选择设备状态"
                >
                  <el-option
                    v-for="(item, index) in stateArr"
                    :key="index"
                    :value="item.value"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="区域1">
              <el-col>
                <el-input
                  v-model="form.area1"
                  placeholder="请输入区域"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域2">
              <el-col>
                <el-input
                  v-model="form.area2"
                  placeholder="请输入区域"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="地址">
              <el-col>
                <el-input
                  v-model="form.equipmentAddr"
                  placeholder="请输入地址"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-form-item label="位置">
            <el-col>
              <el-col :span="8">
                <el-input
                  v-model="form.gpsLng"
                  placeholder="请输入经度"
                ></el-input>
              </el-col>
              <el-col :span="8">
                <el-input
                  v-model="form.gpsLat"
                  placeholder="请输入纬度"
                ></el-input>
              </el-col>
              <el-col :span="8">
                <el-button
                  type="text"
                  icon="el-icon-location"
                  @click="handleShowMap"
                  >选择地图位置</el-button
                >
              </el-col>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="是否关联物联网" prop="relationIot">
              <el-radio-group v-model="form.relationIot">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-form-item style="margin-left:15px">
            <el-button type="primary" @click="handleSubmitForm('deviceForm')">{{
              !id ? '添加设备' : '确认修改'
            }}</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <el-dialog top="0" custom-class="pic-popup" :visible.sync="mapVisible">
      <mapSelect :LngLat="lngLat" :MapClick="mapClick"></mapSelect>
    </el-dialog>
  </div>
</template>
<script>
import deviceMap from '../../components/device/deviceMap'
import deviceState from '../../components/device/deviceState'
import areaSelect from '../../components/common/select/area'
import sceneSelect from '../../components/common/select/sceneEdit'
import deviceTypeSelect from '../../components/common/select/deviceType'
import mapSelect from '../../components/common/ui/mapSelect'

export default {
  name: 'deviceEdit',
  components: {
    deviceMap,
    deviceState,
    areaSelect,
    sceneSelect,
    deviceTypeSelect,
    mapSelect
  },
  data () {
    return {
      gHeight: this.$store.state.gHeight,
      id: this.$route.query.id ? this.$route.query.id : '', // 根据id判断是 新增设备(没有id)) / 编辑设备(有id)
      form: {
        equipmentId: '', // 设备编号
        equipmentModel: '', // 设备型号
        equipmentType: '', // 设备类型
        equipmentName: '', // 设备名称
        equipmentState: '', // 设备状态
        moduleId: '', // 场景
        areaId: '', // 所属
        equipmentMaker: '', // 制造商
        area1: '', // 区域1
        area2: '', // 区域2
        equipmentAddr: '', // 地址
        gpsLng: '', // 经度
        gpsLat: '', // 纬度
        relationIot: 1
      },
      areaIds: {
        areaId1: '', // 所属1级
        areaId2: '', // 所属2级
        areaId3: '' // 所属3级
      },
      modTypes: {
        modType1: '',
        modType2: ''
      },
      parentList: [],
      childList: [],
      stateArr: [], // 设备状态 开、关
      mapVisible: false, // 地图是否显示
      mapClick: true, // 地图标注点是否可切换
      lngLat: { lng: 121.423224, lat: 31.223914 }, // 地图标注点的位置
      rules: {
        equipmentId: [
          { required: true, message: '请输入设备编号', trigger: 'blur' }
        ],
        areaId: [{ required: true, message: '请选择所属', trigger: 'blur' }],
        equipmentName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        equipmentMaker: [
          { required: true, message: '请输入设备制造商', trigger: 'blur' }
        ],
        equipmentModel: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        moduleId: [
          { required: true, message: '场景必须选择', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.handleInit()
  },
  computed: {
    pointData () {
      return this.$store.state.event.pointData
    },
    pointPopShow () {
      return this.$store.state.event.pointPopShow
    }
  },
  watch: {
    pointData: {
      handler (curVal) {
        this.form.gpsLng = curVal.lng
        this.form.gpsLat = curVal.lat
      },
      deep: true
    },
    pointPopShow: {
      handler (curVal) {
        this.mapVisible = curVal
      },
      deep: true
    },
    // 'areaIds.areaId1': {
    //   handler (val) {
    //     // this.parentList = []
    //     // this.childList = []
    //     // this.modTypes.modType1 = ''
    //     // this.modTypes.modType2 = ''
    //   }
    // },
    parentList: {
      handler (arr) {
        this.getSceneByModuleType1(this.modTypes.modType1, arr)
      }
    }
  },
  methods: {
    // 所属一级改变时触发事件
    onAreaFirstChildChange () {
      this.parentList = []
      this.childList = []
      this.modTypes.modType1 = ''
      this.modTypes.modType2 = ''
      this.form.areaId = ''
      this.form.moduleId = ''
      console.log(this.form.areaId)
    },

    // 所属二级改变时触发事件
    onAreaSecondChildChange (id) {
      this.form.areaId = id
      this.parentList = []
      this.childList = []
      this.modTypes.modType1 = ''
      this.modTypes.modType2 = ''
      this.form.moduleId = ''
      this.getSceneByAreaId(id)
    },

    // 获取场景第一个选项的数组
    getSceneByAreaId (deptId) {
      let url = this.$base.getUrl('getModuleInfoTree')
      let params = {
        url: url,
        data: {
          deptId: deptId
        }
      }
      this.$store.dispatch('getForm', params).then((res) => {
        if (res.hasOwnProperty('nodes') && res.nodes.length > 0) {
          let newNodes = []
          res.nodes.forEach((item) => {
            if (item.showFlag !== 0) {
              newNodes.push(item)
            }
          })
          this.parentList = newNodes
        }
      })
    },

    // 获得场景第二个选项的数组
    getSceneByModuleType1 (currentType, arr) {
      if (currentType && arr.length > 0) {
        let o = arr.filter(item => {
          return item.moduleId === currentType
        })
        this.childList = o[0].nodes
      }
    },

    // 第一个场景发生变化时更新第二个场景数组
    firstSelectChange (modType1) {
      this.modTypes.modType2 = ''
      this.form.moduleId = ''
      this.getSceneByModuleType1(modType1, this.parentList)
    },

    // 第二个场景发生变化时更新moduleId
    secondSelectChange (modType2) {
      this.form.moduleId = modType2
    },

    // page init
    handleInit () {
      // 设备状态
      this.stateArr = this.$base.getConst('select', 'deviceState')
      // 如果有传id走编辑设备流程
      this.handleGetCurrentDeviceInfo()
    },
    // 拉取当前设备信息
    handleGetCurrentDeviceInfo () {
      if (this.id) {
        let url = this.$base.getUrl('getEquipmentInfoByNo')
        let params = {
          url: url,
          data: {
            equipmentNo: this.id
          }
        }
        this.$store.dispatch('getForm', params).then((res) => {
          if (res) {
            this.areaIds.areaId1 = res.areaId1
            this.areaIds.areaId2 = res.areaId2
            this.areaIds.areaId3 = res.areaId3
            this.modTypes.modType1 = res.moduleId1
            this.modTypes.modType2 = res.moduleId2

            Object.assign(this.form, res)
            if (this.form.gpsLat && this.form.gpsLng) {
              let arr = this.$base.transCoordinate(
                this.form.gpsLng,
                this.form.gpsLat,
                res.mapType
              )
              this.lngLat.lng = arr[0].toFixed(6)
              this.lngLat.lat = arr[1].toFixed(6)
            }
          }
          this.getSceneByAreaId(res.areaId)
        })
      }
    },
    // 提交表单
    handleSubmitForm (formName) {
      let url
      if (!this.id) {
        url = this.$base.getUrl('addEquipmentInfo') // 添加设备
      } else {
        url = this.$base.getUrl('updateEquipmentInfo') // 修改设备
      }

      let params = {
        isJson: true,
        url: url,
        data: this.form
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('postForm', params).then((res) => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: !this.id ? '新增成功! ' : '修改成功！'
              })
              this.$router.push({
                name: 'deviceSearch'
              })
            } else {
              this.$message({
                type: 'danger',
                message: res.msg
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 选择地图位置
    handleShowMap () {
      this.mapVisible = true
      this.$store.commit('setPointPopShow', true)
    },
    // 所属变化时
    onAreaChange (val) {
      this.form.areaId = val
      this.getSceneByAreaId(val)
    },

    onDeviceChange (val) {
      this.form.equipmentType = val
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.name !== 'deviceSearch') {
      this.$store.commit('keepOut')
    }
    next()
  }
}
</script>
<style scoped>
.el-dialog__wrapper >>> .pic-popup {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: auto;
  margin: 0;
}

.el-dialog__wrapper >>> .el-dialog__body {
  padding: 20px;
}

.el-dialog__wrapper >>> .el-dialog__header {
  padding: 10px 20px 10px;
}

.el-dialog__wrapper >>> .el-dialog__headerbtn {
  top: 10px;
}
</style>
